home *** CD-ROM | disk | FTP | other *** search
- Path: news.vais.net!news
- From: Chalrie Fink <cfink@aecsoft.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Any way to restrict casting?
- Date: Thu, 22 Feb 1996 08:34:25 -0500
- Organization: AEC Software
- Message-ID: <312C70E1.44AE@aecsoft.com>
- References: <4gfuj4$1cu@news.mistral.co.uk>
- NNTP-Posting-Host: pm01-s07.vais.net
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (Win95; I)
-
- Alan Campbell wrote:
- >
- > Using Borland C++ 3.1, I find I can coerce a pointer to an instance of
- > a class into a pointer to *anything*. Like an int.
- >
- > e.g.:
- >
- > #include <iostream.h>
- > #include <string.h>
- >
- > class Base {
- >
- > public:
- > int iFieldb;
- > char cFieldb;
- > char sFieldb[10];
- >
- > };
- >
- > class Derived: public Base {
- >
- > public:
- > int iFieldd;
- > char cFieldd;
- > char sFieldd[10];
- > };
- >
- > int main()
- > {
- >
- > Base aBase;
- > Derived aDerived;
- >
- > aBase.iFieldb = 10;
- > aBase.cFieldb = 'a';
- > strcpy(aBase.sFieldb,"abcdefghi");
- >
- > aDerived.iFieldd = 210;
- > aDerived.cFieldd = 'ba';
- > strcpy(aDerived.sFieldd,"jklmnopqr");
- >
- > Base* ptrBase = &aBase;
- > cout << "aDerived's sFieldb: " << ptrBase->sFieldb << endl;
- >
- > Derived* ptrDerived = &aDerived;
- > cout << "aDerived's sFieldd: " << ptrDerived->sFieldd << endl;
- >
- > // this is stupid, but it works
- >
- > ptrDerived = (Derived*) ptrBase;
- >
- > cout << "aBase's sFieldd, treated as a Derived: " <<
- > ptrDerived->sFieldd << endl;
- >
- > int anInt;
- >
- > // this is even stupider; taking a data member of an int!
- >
- > ptrDerived = (Derived*) &anInt;
- > cout << "anInt's sFieldd, treated as a Derived: " <<
- > ptrDerived->sFieldd << endl;
- >
- > return 1;
- >
- > };
- >
- > Is this valid in all dialects of C++? Is it part of the standard? If
- > so, ouch.
- >
- > Yours,
- >
- > Alan Campbell
- > Brighton, UK
- >
- > <<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>
-
- Allan:
-
- If you don't like it, just don't do it!
-